package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xinchuang.comment.R;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.target.TargetBaseData;
import com.xinchuang.entity.target.TargetCommonAttribute;
import com.xinchuang.entity.targetSystem.RangeType;
import com.xinchuang.entity.targetSystem.scene.SceneIndexList;
import com.xinchuang.entity.targetSystem.scene.SceneSubList;
import com.xinchuang.entity.targetSystem.scene.SceneSystemsList;
import com.xinchuang.entity.targetSystem.scene.SceneTargetList;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.entity.targetSystem.target.*;
import com.xinchuang.exception.CustomException;
import com.xinchuang.mapper.targetSystem.*;
import com.xinchuang.mapper.targetSystem.target.SystemsRangeMapper;
import com.xinchuang.mapper.targetSystem.target.SystemsRangeTypeMapper;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.target.TargetBaseDataService;
import com.xinchuang.service.targetSystem.OverallAnalyseService;
import com.xinchuang.service.targetSystem.SystemElseService;
import com.xinchuang.service.targetSystem.SystemsDynamicService;
import com.xinchuang.service.targetSystem.scene.SceneIndexListService;
import com.xinchuang.service.targetSystem.scene.SceneSubListService;
import com.xinchuang.service.targetSystem.scene.SceneSystemsListService;
import com.xinchuang.service.targetSystem.scene.SceneTargetListService;
import com.xinchuang.service.targetSystem.target.PostureComputeTypeService;
import com.xinchuang.service.targetSystem.target.SystemIndexService;
import com.xinchuang.service.targetSystem.target.TargetPostureMsgTableService;
import com.xinchuang.service.targetSystem.target.TargetPostureRelationTableService;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.LngLatUtil;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.utils.ObjectUtil;
import com.xinchuang.utils.RedisName;
import com.xinchuang.vo.*;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.PortableServer.POA;
import org.springframework.expression.spel.ast.OpNE;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.ObjectName;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2024/3/7 16:21
 */
@Service
@RequiredArgsConstructor
public class SystemElseServiceImpl implements SystemElseService {

    private final KeyWordSystem keyWordSystem;

    private final TargetTypeMapper targetTypeMapper;

    private final TargetBaseDataService targetBaseDataService;

    private final RedisUtil redisUtil;

    private final SystemsMasterMapper systemsMasterMapper;

    private final SystemPositionMapper systemPositionMapper;

    private final TargetPostureRelationTableService targetPostureRelationTableService;

    private final TargetPostureMsgTableService targetPostureMsgTableService;

    private final SystemsRelationMapper systemsRelationMapper;

    private final SystemsRangeMapper systemsRangeMapper;

    private final SystemsRangeTypeMapper systemsRangeTypeMapper;

    private final RedisUseService redisUseService;

    private final RangeTypeMapper rangeTypeMapper;

    private final SystemIndexService systemIndexService;

    private final SceneSystemsListService sceneSystemsListService;

    private final SceneIndexListService sceneIndexListService;

    private final SceneTargetListService sceneTargetListService;

    private final SceneSubListService sceneSubListService;

    private final SystemsDynamicService systemsDynamicService;

    private final PostureComputeTypeService postureComputeTypeService;

    private final TargetMapper targetMapper;

    private final OverallAnalyseService overall;

    @Override
    public List<Map<String, Object>> selectTargetTypeList(Set set) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<TargetType> targetTypes = targetTypeMapper.findAll();
        if (CollectionUtil.isNotEmpty(targetTypes)) {
            Map<String, Object> map;
            for (TargetType targetType : targetTypes) {
                if ("0".equals(targetType.getParentId())) {
                    continue;
                }
                map = new HashMap<>(4);
                if ("1".equals(targetType.getLevel())) {
                    map.put("sId", targetType.getTypeId());
                    map.put("systemName", targetType.getTypeName());
                    map.put("children", getTreeChild(targetType.getTypeId(), targetTypes, set));
                    if (set.contains(targetType.getTypeId())) {
                        map.put("random", true);
                    } else {
                        map.put("random", false);
                    }
                    resultList.add(map);
                }
            }
        }
        return resultList;
    }

    /**
     * 递归查询子节点目标树
     *
     * @param id
     * @param allTree
     * @param set
     * @return
     */
    private List<Map<String, Object>> getTreeChild(String id, List<TargetType> allTree, Set set) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("sId", targetType.getTypeId());
                map.put("systemName", targetType.getTypeName());
                if (set.contains(targetType.getTypeId())) {
                    map.put("random", true);
                } else {
                    map.put("random", false);
                }
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String sId = (String) map.get("sId");
            map.put("children", getTreeChild(sId, allTree, set));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    @Override
    public List<Map<String, Object>> selectTypeTargetList(String typeId, String keyword, String country, Set set) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<TargetBaseData> list = targetBaseDataService.lambdaQuery()
                .eq(TargetBaseData::getType, typeId)
                .eq(StringUtils.isNotBlank(country), TargetBaseData::getCountry, country)
                .like(StringUtils.isNotBlank(keyword), TargetBaseData::getTargetName, keyword)
                .eq(TargetBaseData::getDeleteSign, 1)
                .list();
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Object> map;
            for (TargetBaseData targetBaseData : list) {
                if (set.contains(targetBaseData.getTargetId())) {
                    continue;
                }
                map = new HashMap<>(3);
                map.put("targetId", targetBaseData.getTargetId());
                map.put("targetName", targetBaseData.getTargetName());
                resultList.add(map);
            }
        }
        return resultList;
    }

    @Override
    public void moveTarget(List<String> typeList, String typeRedis, List<String> targetList, String targetRedis, String onTargetRedis) {
        //已选全部目标
        Set targetSet = new HashSet();
        if (redisUtil.hasKey(targetRedis)) {
            targetSet = redisUtil.sGet(targetRedis);
        }
        //已选单个目标
        Set onTarget = new HashSet();
        if (redisUtil.hasKey(onTargetRedis)) {
            onTarget = redisUtil.sGet(onTargetRedis);
        }
        //处理类型列表
        if (CollectionUtil.isNotEmpty(typeList)) {
            Set typeSet;
            if (redisUtil.hasKey(typeRedis)) {
                typeSet = redisUtil.sGet(typeRedis);
            } else {
                typeSet = new HashSet();
            }
            for (String s : typeList) {
                //保存选择的类型下所有目标
                if (!typeSet.contains(s)) {
                    List<TargetBaseData> list = targetBaseDataService.lambdaQuery()
                            .eq(TargetBaseData::getType, s)
                            .eq(TargetBaseData::getDeleteSign, 1)
                            .list();
                    if (CollectionUtil.isNotEmpty(list)) {
                        for (TargetBaseData targetBaseData : list) {
                            targetSet.add(targetBaseData.getTargetId());
                            onTarget.remove(targetBaseData.getTargetId());
                        }
                    }
                }
                typeSet.add(s);
            }
            redisUtil.del(typeRedis);
            if (CollectionUtil.isNotEmpty(typeSet)) {
                redisUtil.sSet(typeRedis, typeSet.toArray());
            }
            redisUtil.del(onTargetRedis);
            if (CollectionUtil.isNotEmpty(onTarget)) {
                redisUtil.sSet(onTargetRedis, onTarget.toArray());
            }
        }
        //单选目标列表
        if (CollectionUtil.isNotEmpty(targetList)) {
            for (String s : targetList) {
                onTarget.add(s);
                targetSet.add(s);
            }
        }
        redisUtil.del(onTargetRedis);
        if (CollectionUtil.isNotEmpty(onTarget)) {
            redisUtil.sSet(onTargetRedis, onTarget.toArray());
        }
        redisUtil.del(targetRedis);
        if (CollectionUtil.isNotEmpty(targetSet)) {
            redisUtil.sSet(targetRedis, targetSet.toArray());
        }
    }

    /**
     * 处理取消选择类型后已选目标的处理
     *
     * @param typeId
     * @param targetRedis
     */
    private void delSetList(String typeId, String targetRedis, int sign, String targetId) {
        //已选全部目标
        Set targetSet = new HashSet();
        if (redisUtil.hasKey(targetRedis)) {
            targetSet = redisUtil.sGet(targetRedis);
        }
        if (sign == 1) {
            if (CollectionUtil.isNotEmpty(targetSet)) {
                List<TargetBaseData> list = targetBaseDataService.lambdaQuery()
                        .eq(TargetBaseData::getType, typeId)
                        .list();
                if (CollectionUtil.isNotEmpty(list)) {
                    for (TargetBaseData targetBaseData : list) {
                        targetSet.remove(targetBaseData.getTargetId());
                    }
                }
            }
        } else {
            targetSet.remove(targetId);
        }
        redisUtil.del(targetRedis);
        if (CollectionUtil.isNotEmpty(targetSet)) {
            redisUtil.sSet(targetRedis, targetSet.toArray());
        }
    }

    @Override
    public void pushTarget(String typeRedis, List<String> targetList, String targetRedis, String onTargetRedis) {
        if (CollectionUtil.isNotEmpty(targetList)) {
            //独立目标
            Set onTarget = new HashSet();
            if (redisUtil.hasKey(onTargetRedis)) {
                onTarget = redisUtil.sGet(onTargetRedis);
            }
            //类型选择
            Set typeSet = new HashSet();
            if (redisUtil.hasKey(typeRedis)) {
                typeSet = redisUtil.sGet(typeRedis);
            }
            for (String s : targetList) {
                if (CollectionUtil.isNotEmpty(onTarget)) {
                    if (onTarget.contains(s)) {
                        delSetList(s, targetRedis, 2, s);
                        onTarget.remove(s);
                        continue;
                    }
                }
                if (CollectionUtil.isNotEmpty(typeSet)) {
                    if (typeSet.contains(s)) {
                        delSetList(s, targetRedis, 1, null);
                        typeSet.remove(s);
                        continue;
                    }
                }
            }
            redisUtil.del(onTargetRedis);
            if (CollectionUtil.isNotEmpty(onTarget)) {
                redisUtil.sSet(onTargetRedis, onTarget.toArray());
            }
            redisUtil.del(typeRedis);
            if (CollectionUtil.isNotEmpty(typeSet)) {
                redisUtil.sSet(typeRedis, typeSet.toArray());
            }
        }
    }

    @Override
    public List<Map<String, Object>> selectTargetList(String typeKey, String onKey) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //查询类型
        Set typeSet = new HashSet();
        if (redisUtil.hasKey(typeKey)) {
            typeSet = redisUtil.sGet(typeKey);
        }
        if (CollectionUtil.isNotEmpty(typeSet)) {
            List<TargetType> targetTypes = targetTypeMapper.selectList(new LambdaQueryWrapper<TargetType>().in(TargetType::getTypeId, typeSet.toArray()));
            if (CollectionUtil.isNotEmpty(targetTypes)) {
                Map<String, Object> map;
                for (TargetType targetType : targetTypes) {
                    map = new HashMap<>(4);
                    map.put("stId", targetType.getTypeId());
                    map.put("name", targetType.getTypeName() + "(类型)");
                    resultList.add(map);
                }
            }
        }
        //查询目标
        Set targetSet = new HashSet();
        if (redisUtil.hasKey(onKey)) {
            targetSet = redisUtil.sGet(onKey);
        }
        if (CollectionUtil.isNotEmpty(targetSet)) {
            List<TargetBaseData> list = targetBaseDataService.lambdaQuery()
                    .in(TargetBaseData::getTargetId, targetSet.toArray())
                    .eq(TargetBaseData::getDeleteSign, 1)
                    .list();
            if (CollectionUtil.isNotEmpty(list)) {
                Map<String, Object> map;
                for (TargetBaseData targetBaseData : list) {
                    map = new HashMap<>(4);
                    map.put("stId", targetBaseData.getTargetId());
                    map.put("name", targetBaseData.getTargetName() + "(目标)");
                    resultList.add(map);
                }
            }
        }
        return resultList;
    }

    @Override
    public Map<String, Object> selectSystemTree(String sysId, String name) {
        Map<String, Object> main = new HashMap<>();
        main.put("sysId", sysId);
        main.put("systemsName", name);
        main.put("systems", true);
        main.put("position", new ArrayList<>());
        main.put("height", 0);
        main.put("viewDistances", new ArrayList<>());
        main.put("diffType", 1);
        SystemPosition position = systemPositionMapper.getPositionById(sysId);
        if (ObjectUtil.isNotEmpty(position)) {
            main.put("position", FileElseUtil.getStringTransitionList(position.getPositions()));
            main.put("height", StringUtils.isNotBlank(position.getHeight()) ? position.getHeight() : 0);
            main.put("viewDistances", FileElseUtil.getStringTransitionList(position.getViewDistances()));
        }
        //体系子类数据
        List<Map<String, Object>> mainSub = new ArrayList<>();
        //类型
        List<TargetType> targetTypes = systemPositionMapper.selectSystemsRelationTypeList(sysId);
        if (CollectionUtil.isNotEmpty(targetTypes)) {
            Map<String, Object> map;
            for (TargetType targetType : targetTypes) {
                map = new HashMap<>();
                map.put("sId", targetType.getTypeId());
                map.put("systemName", targetType.getTypeName());
                map.put("position", new ArrayList<>());
                map.put("height", 0);
                map.put("viewDistances", new ArrayList<>());
                map.put("diffType", 2);
                List<Map<String, Object>> targetMap = new ArrayList<>();
                //目标
                List<TargetBaseData> targetList = systemPositionMapper.selectTypeTargetList(sysId, targetType.getTypeId());
                if (CollectionUtil.isNotEmpty(targetList)) {
                    Map<String, Object> target;
                    for (TargetBaseData data : targetList) {
                        target = new HashMap<>();
                        target.put("targetId", data.getTargetId());
                        target.put("targetName", data.getTargetName());
                        target.put("height", 0);
                        target.put("viewDistances", new ArrayList<>());
                        target.put("diffType", 4);
                        SystemPosition targetPosition = systemPositionMapper.getPositionById(data.getTargetId());
                        if (null != targetPosition) {
                            target.put("height", StringUtils.isNotBlank(targetPosition.getHeight()) ? targetPosition.getHeight() : 0);
                            target.put("viewDistances", FileElseUtil.getStringTransitionList(targetPosition.getViewDistances()));
                        }
                        target.put("position", Arrays.asList(Double.valueOf(data.getLon()), Double.valueOf(data.getLat()), 0));
                        target.put("children", new ArrayList<>());
                        targetMap.add(target);
                    }
                }
                map.put("children", targetMap);
                mainSub.add(map);
            }
        }
        //封装态势目标列表
        Map<String, Object> postureMap = new HashMap<>();
        postureMap.put("sId", "0");
        postureMap.put("systemName", "态势目标");
        postureMap.put("position", new ArrayList<>());
        postureMap.put("height", 0);
        postureMap.put("viewDistances", new ArrayList<>());
        postureMap.put("diffType", 3);
        List<Map<String, Object>> postureList = new ArrayList<>();
        List<TargetPostureRelationTable> relationTables = targetPostureRelationTableService
                .lambdaQuery()
                .eq(TargetPostureRelationTable::getTargetId, sysId)
                .list();
        if (CollectionUtil.isNotEmpty(relationTables)) {
            Map<String, Object> postureSubMap;
            for (TargetPostureRelationTable relationTable : relationTables) {
                List<TargetPostureMsgTable> postureMsgTables = targetPostureMsgTableService.lambdaQuery()
                        .eq(TargetPostureMsgTable::getPostureId, relationTable.getPostureId())
                        .in(TargetPostureMsgTable::getKeyId, "targetName", "position")
                        .list();
                if (CollectionUtil.isNotEmpty(postureMsgTables)) {
                    postureSubMap = new HashMap<>();
                    postureSubMap.put("targetId", postureMsgTables.get(0).getPostureId());
                    postureSubMap.put("targetName", "");
                    postureSubMap.put("height", 0);
                    postureSubMap.put("viewDistances", new ArrayList<>());
                    postureSubMap.put("diffType", 6);
                    SystemPosition targetPosition = systemPositionMapper.getPositionById(postureMsgTables.get(0).getPostureId());
                    if (null != targetPosition) {
                        postureSubMap.put("height", StringUtils.isNotBlank(targetPosition.getHeight()) ? targetPosition.getHeight() : 0);
                        postureSubMap.put("viewDistances", FileElseUtil.getStringTransitionList(targetPosition.getViewDistances()));
                    }
                    postureList.add(postureSubMap);
                    for (TargetPostureMsgTable postureMsgTable : postureMsgTables) {
                        switch (postureMsgTable.getKeyId()) {
                            case "targetName":
                                postureSubMap.put("targetName", FileElseUtil.getStringTransitionString(postureMsgTable.getKeyValue()));
                                break;
                            case "position":
                                postureSubMap.put("position", FileElseUtil.getStringTransitionList(postureMsgTable.getKeyValue()));
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        postureMap.put("children", postureList);
        mainSub.add(postureMap);
        main.put("children", mainSub);
        return main;
    }

    @Override
    @Transactional
    public Result systemRangeDeo(SystemsRangeVo systemsRangeVo) {
        if (null == systemsRangeVo.getType()) {
            return ResultUtil.error(500, "操作异常请重试");
        }
        Map<String, Object> resultMap = new HashMap<>();
        if (1 == systemsRangeVo.getType()) {
            List<Map<String, Object>> m1 = new ArrayList<>();
            List<Map<String, Object>> m2 = new ArrayList<>();
            List<SystemsRangeType> rangeTypes = systemsRangeTypeMapper.selectList(new QueryWrapper<SystemsRangeType>()
                    .lambda()
                    .eq(SystemsRangeType::getSysId, systemsRangeVo.getSysId())
                    .eq(StringUtils.isNotBlank(systemsRangeVo.getTargetId()), SystemsRangeType::getTargetId, systemsRangeVo.getTargetId())
                    .orderByAsc(SystemsRangeType::getTargetId)
            );
            for (SystemsRangeType data : rangeTypes) {
                Map<String, Object> map = new HashMap<>();
                map.put("rangeTypeId", data.getId());
                map.put("rangeName", FileElseUtil.getObjectToString(data.getRangeName()));
                map.put("range", FileElseUtil.getObjectToDouble(data.getRadius()));
                map.put("targetName", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + data.getTargetId(), "targetName")));
                m2.add(map);
                if (null != data.getShowType() && 1 == data.getShowType()) {
                    m1.add(map);
                }
            }
            resultMap.put("chooseList", m1);
            resultMap.put("noChooseList", m2);
            return ResultUtil.success(resultMap);
        } else if (2 == systemsRangeVo.getType()) {
            SystemsRangeType rangeType = systemsRangeTypeMapper.selectById(systemsRangeVo.getRangeTypeId());
            if (ObjectUtil.isNotEmpty(rangeType)) {
                //清理缓存
                String redisKey;
                if (StringUtils.isNotBlank(rangeType.getTargetId())) {
                    redisKey = RedisName.SYSTEMS_TARGET_RANGE_LIST + "_" + rangeType.getSysId() + "_" + rangeType.getTargetId();
                } else {
                    redisKey = RedisName.SYSTEMS_TARGET_RANGE_LIST + "_" + rangeType.getSysId();
                }
                redisUtil.hdel(redisKey, rangeType.getId());
                systemsRangeTypeMapper.deleteById(systemsRangeVo.getRangeTypeId());
                return ResultUtil.success("删除成功", null);
            }
            return ResultUtil.error(500, "删除失败/数据不存在");
        } else if (3 == systemsRangeVo.getType()) {
            SystemsRangeType rangeType = systemsRangeTypeMapper.selectById(systemsRangeVo.getRangeTypeId());
            if (ObjectUtil.isEmpty(rangeType)) {
                return ResultUtil.error(500, "数据已删除/不存在");
            }
            resultMap.put("rangeTypeId", rangeType.getId());
            resultMap.put("rangeName", rangeType.getRangeName());
            resultMap.put("range", FileElseUtil.getObjectToDouble(rangeType.getRadius()));
            resultMap.put("rangeId", rangeType.getRangeId());
            resultMap.put("height", FileElseUtil.getObjectToDouble(rangeType.getHeight()));
            resultMap.put("angle", FileElseUtil.getObjectToDouble(rangeType.getAngle()));
            List<SystemsRange> systemsRanges = systemsRangeMapper.selectList(
                    new LambdaQueryWrapper<SystemsRange>()
                            .eq(SystemsRange::getRedId, rangeType.getId())
            );
            resultMap.put("targetList", CollectionUtil.isNotEmpty(systemsRanges) ? systemsRanges : ListUtil.empty());
        } else if (4 == systemsRangeVo.getType()) {
            String rangeTypeId = systemsRangeVo.getRangeTypeId();
            SystemsRangeType rangeType = systemsRangeTypeMapper.selectById(rangeTypeId);
            if (ObjectUtil.isEmpty(rangeType)) {
                rangeType = new SystemsRangeType();
                rangeType.setSysId(systemsRangeVo.getSysId());
                rangeType.setTargetId(systemsRangeVo.getTargetId());
                rangeType.setRangeName(systemsRangeVo.getRangeName());
                rangeType.setRadius(systemsRangeVo.getRange());
                rangeType.setHeight(systemsRangeVo.getHeight());
                rangeType.setAngle(systemsRangeVo.getAngle());
                rangeType.setRangeId(systemsRangeVo.getRangeId());
                rangeType.setShowType(2);
                systemsRangeTypeMapper.insert(rangeType);
            } else {
                rangeType.setRangeName(systemsRangeVo.getRangeName());
                rangeType.setRadius(systemsRangeVo.getRange());
                rangeType.setHeight(systemsRangeVo.getHeight());
                rangeType.setAngle(systemsRangeVo.getAngle());
                rangeType.setRangeId(systemsRangeVo.getRangeId());
                systemsRangeTypeMapper.updateById(rangeType);
            }
            resultMap.put("rangeTypeId", rangeType.getId());
            resultMap.put("rangeName", rangeType.getRangeName());
            resultMap.put("range", FileElseUtil.getObjectToDouble(systemsRangeVo.getRange()));
            resultMap.put("rangeId", systemsRangeVo.getRangeId());
            resultMap.put("height", FileElseUtil.getObjectToDouble(systemsRangeVo.getHeight()));
            resultMap.put("angle", FileElseUtil.getObjectToDouble(systemsRangeVo.getAngle()));
            resultMap.put("targetList", getSysTargetRange(rangeType.getId(), systemsRangeVo));
        } else if (5 == systemsRangeVo.getType()) {
            systemsRangeTypeMapper.update(null, new LambdaUpdateWrapper<SystemsRangeType>()
                    .set(SystemsRangeType::getShowType, 2)
                    .eq(SystemsRangeType::getSysId, systemsRangeVo.getSysId())
                    .eq(StringUtils.isNotBlank(systemsRangeVo.getTargetId()), SystemsRangeType::getTargetId, systemsRangeVo.getTargetId()));
            if (StringUtils.isBlank(systemsRangeVo.getTargetId())) {
                List<String> targetList = systemsRangeTypeMapper.getSysRangeTargetList(systemsRangeVo.getSysId());
                if (CollectionUtil.isNotEmpty(targetList)) {
                    for (String id : targetList) {
                        redisUseService.deleteSystemsRelationRangeValue(systemsRangeVo.getSysId(), id, false);
                    }
                }
            } else {
                redisUseService.deleteSystemsRelationRangeValue(systemsRangeVo.getSysId(), systemsRangeVo.getTargetId(), false);
            }
            if (CollectionUtil.isNotEmpty(systemsRangeVo.getChooseList())) {
                List<String> ids = new ArrayList<>();
                for (SystemsRangeDataVo data : systemsRangeVo.getChooseList()) {
                    ids.add(data.getRangeTypeId());
                }
                LambdaUpdateWrapper<SystemsRangeType> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(SystemsRangeType::getShowType, 1);
                wrapper.in(SystemsRangeType::getId, ids);
                systemsRangeTypeMapper.update(null, wrapper);
                List<SystemsRangeType> rangeTypes = systemsRangeTypeMapper
                        .selectList(new LambdaQueryWrapper<SystemsRangeType>()
                        .in(SystemsRangeType::getId, ids));
                if (CollectionUtil.isNotEmpty(rangeTypes)) {
                    for (SystemsRangeType rangeType : rangeTypes) {
                        redisUseService.updateSystemsRelationRangeValue(
                                rangeType.getSysId(),
                                rangeType.getTargetId(),
                                rangeType.getId(),
                                JSON.toJSONString(rangeType)
                        );
                    }
                }
            }
        }
        return ResultUtil.success(resultMap);
    }

    private List<SystemsRange> getSysTargetRange(String id, SystemsRangeVo systemsRangeVo) {
        List<SystemsRange> list = new ArrayList<>();
        //计算覆盖范围内的目标
        //当前体系所有关联目标
        List<String> strings = redisUseService.getSystemsTargetList(systemsRangeVo.getSysId());
        TargetBaseData one = targetBaseDataService.lambdaQuery()
                .eq(TargetBaseData::getTargetId, systemsRangeVo.getTargetId())
                .one();
        List<TargetBaseData> baseData = targetBaseDataService.lambdaQuery()
                .in(TargetBaseData::getTargetId, strings)
                .list();
        systemsRangeMapper.delete(new LambdaQueryWrapper<SystemsRange>()
                .eq(SystemsRange::getRedId, id));
        SystemsRange map;
        for (TargetBaseData baseDatum : baseData) {
            if (baseDatum.getTargetId().equals(systemsRangeVo.getTargetId())) {
                continue;
            }
            //计算范围
            double distance = LngLatUtil.getDistance(Double.parseDouble(one.getLon()), Double.parseDouble(one.getLat()), Double.parseDouble(baseDatum.getLon()), Double.parseDouble(baseDatum.getLat()));
            if (distance <= systemsRangeVo.getRange()) {
                map = new SystemsRange();
                map.setRedId(id);
                map.setTargetId(baseDatum.getTargetId());
                map.setTargetName(baseDatum.getTargetName());
                map.setDistance(FileElseUtil.getObjectToDouble(distance) + "km");
                list.add(map);
                systemsRangeMapper.insert(map);
            }
        }
        return list;
    }

    @Override
    public Result addSystemsTargetActionRange(SystemsRangeVo systemsRangeVo) {
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("range", 0);
        resultMap.put("positions", new ArrayList<>());
        List<SystemsRange> list = new ArrayList<>();
        SystemsRelation selectOne = systemsRelationMapper.selectOne(new QueryWrapper<SystemsRelation>()
                .lambda()
                .eq(SystemsRelation::getSysId, systemsRangeVo.getSysId())
                .eq(SystemsRelation::getTargetId, systemsRangeVo.getTargetId()));
        if (ObjectUtil.isNotEmpty(selectOne)) {
            if (systemsRangeVo.getJudge()) {
                RangeType type = rangeTypeMapper.selectById(systemsRangeVo.getRangeId());
                if (ObjectUtil.isEmpty(type)) {
                    throw new CustomException(500, "请选择作用范围的类型");
                }
                selectOne.setRangeId(systemsRangeVo.getRangeId());
                selectOne.setRangeValue(FileElseUtil.getObjectToDouble(systemsRangeVo.getRange()));
                selectOne.setHeight(systemsRangeVo.getHeight());
                selectOne.setAngle(systemsRangeVo.getAngle());
                systemsRelationMapper.updateById(selectOne);
                SystemsRangeType systemsRangeType = systemsRangeTypeMapper.selectOne(
                        new LambdaQueryWrapper<SystemsRangeType>()
                                .eq(SystemsRangeType::getTargetId, systemsRangeVo.getTargetId())
                                .eq(SystemsRangeType::getSysId, systemsRangeVo.getSysId())
                                .last("LIMIT 1")
                );
                if (ObjectUtil.isNotEmpty(systemsRangeType)) {
                    systemsRangeType.setRadius(FileElseUtil.getObjectToDouble(systemsRangeVo.getRange()));
                    systemsRangeType.setRangeId(systemsRangeVo.getRangeId());
                    systemsRangeType.setHeight(systemsRangeVo.getHeight());
                    systemsRangeType.setAngle(systemsRangeVo.getAngle());
                    systemsRangeTypeMapper.updateById(systemsRangeType);
                } else {
                    systemsRangeType = new SystemsRangeType();
                    systemsRangeType.setSysId(systemsRangeVo.getSysId());
                    systemsRangeType.setTargetId(systemsRangeVo.getTargetId());
                    systemsRangeType.setRadius(FileElseUtil.getObjectToDouble(systemsRangeVo.getRange()));
                    systemsRangeType.setRangeId(systemsRangeVo.getRangeId());
                    systemsRangeType.setHeight(systemsRangeVo.getHeight());
                    systemsRangeType.setAngle(systemsRangeVo.getAngle());
                    systemsRangeTypeMapper.insert(systemsRangeType);
                }
                redisUseService.updateSystemsRelationRangeValue(
                        systemsRangeVo.getSysId(),
                        systemsRangeVo.getTargetId(),
                        systemsRangeType.getId(),
                        JSON.toJSONString(systemsRangeType));
                //计算覆盖范围内的目标
                List<String> strings = systemsRelationMapper.selectSystemsTargetId(systemsRangeVo.getSysId());
                TargetBaseData one = targetBaseDataService.lambdaQuery()
                        .eq(TargetBaseData::getTargetId, systemsRangeVo.getTargetId())
                        .one();
                List<TargetBaseData> baseData = targetBaseDataService.lambdaQuery()
                        .in(TargetBaseData::getTargetId, strings)
                        .list();
                systemsRangeMapper.delete(new LambdaQueryWrapper<SystemsRange>()
                        .eq(SystemsRange::getSysId, systemsRangeVo.getSysId())
                        .eq(SystemsRange::getRedId, systemsRangeVo.getTargetId()));
                SystemsRange map;
                for (TargetBaseData baseDatum : baseData) {
                    if (baseDatum.getTargetId().equals(systemsRangeVo.getTargetId())) {
                        continue;
                    }
                    //计算范围
                    double distance = LngLatUtil.getDistance(Double.parseDouble(one.getLon()), Double.parseDouble(one.getLat()), Double.parseDouble(baseDatum.getLon()), Double.parseDouble(baseDatum.getLat()));
                    if (distance <= systemsRangeVo.getRange()) {
                        map = new SystemsRange();
                        map.setSysId(systemsRangeVo.getSysId());
                        map.setRedId(systemsRangeVo.getTargetId());
                        map.setTargetId(baseDatum.getTargetId());
                        map.setTargetName(baseDatum.getTargetName());
                        map.setDistance(FileElseUtil.getObjectToDouble(distance) + "km");
                        list.add(map);
                        systemsRangeMapper.insert(map);
                    }
                }
                resultMap.put("range", FileElseUtil.getObjectToDouble(systemsRangeVo.getRange()));
                resultMap.put("rangeId", systemsRangeVo.getRangeId());
                resultMap.put("height", FileElseUtil.getObjectToDouble(systemsRangeVo.getHeight()));
                resultMap.put("angle", FileElseUtil.getObjectToDouble(systemsRangeVo.getAngle()));
            } else {
                List<SystemsRange> ranges = systemsRangeMapper.selectList(
                        new LambdaQueryWrapper<SystemsRange>()
                                .eq(SystemsRange::getSysId, systemsRangeVo.getSysId())
                                .eq(SystemsRange::getRedId, systemsRangeVo.getTargetId())
                );
                if (CollectionUtil.isNotEmpty(ranges)) {
                    list = ranges;
                }
                resultMap.put("range", FileElseUtil.getObjectToDouble(selectOne.getRangeValue()));
                resultMap.put("rangeId", selectOne.getRangeId());
                resultMap.put("height", FileElseUtil.getObjectToDouble(selectOne.getHeight()));
                resultMap.put("angle", FileElseUtil.getObjectToDouble(selectOne.getAngle()));
            }
        }
        resultMap.put("targetList", list);
        return ResultUtil.success(resultMap);
    }

    @Override
    public List<Map<String, Object>> getSystemsTargetIndexList(String sysId) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        //当前体系所有关联目标
        List<String> targetIds = redisUseService.getSystemsTargetList(sysId);

        if (CollectionUtil.isEmpty(targetIds)) {
            targetIds = new ArrayList<>();
        }

        Map<Object, Object> relation = redisUseService.getSystemsRelation(sysId);
        if (CollectionUtil.isNotEmpty(relation)) {
            for (Object id : relation.keySet()) {
                List<String> subIds = redisUseService.getSystemsTargetList(id.toString());
                if (CollectionUtil.isNotEmpty(subIds)) {
                    targetIds.addAll(subIds);
                }
            }
        }

//        List<String> targetIds = systemsRelationMapper.selectSystemsTargetId(sysId);
        if (CollectionUtil.isNotEmpty(targetIds)) {
            List<TargetBaseData> dataList = targetBaseDataService.lambdaQuery()
                    .in(TargetBaseData::getTargetId, targetIds.toArray())
//                    .orderByDesc(TargetBaseData::getIndexValue)
                    .last("order by field (grade,'一级','二级','三级') ASC, index_value DESC")
                    .list();
            if (CollectionUtil.isNotEmpty(dataList)) {
//                int length = dataList.size() / 3;
//
//                if (0 == length) {
//                    length = 1;
//                }

//                {
//                    Map<String, Object> main = new HashMap<>(7);
//                    List<Map<String, Object>> subList = new ArrayList<>();
//                    main.put("id", 1);
//                    main.put("grade", "首要");
//                    main.put("targetName", "");
//                    main.put("geographic", "");
//                    main.put("score", "");
//                    main.put("degree", "");
//                    for (int i = 0; i < length; i++) {
//                        TargetBaseData data = dataList.get(i);
//                        Map<String, Object> sub = new HashMap<>(7);
//                        sub.put("id", data.getTargetId());
//                        sub.put("grade", "");
//                        sub.put("targetName", data.getTargetName());
//                        sub.put("geographic", data.getCountry());
//                        sub.put("score", data.getIndexValue());
//                        sub.put("degree", StringUtils.isNotBlank(data.getRisk()) ? data.getRisk() : "无");
//                        subList.add(sub);
//                    }
//
//                    main.put("children", subList);
//                    resultList.add(main);
//                }

//                {
//                    if (dataList.size() > length) {
//                        Map<String, Object> main = new HashMap<>(7);
//                        List<Map<String, Object>> subList = new ArrayList<>();
//                        main.put("id", 2);
//                        main.put("grade", "重要");
//                        main.put("targetName", "");
//                        main.put("geographic", "");
//                        main.put("score", "");
//                        main.put("degree", "");
//                        for (int i = length; i < (dataList.size() > length * 2 ? length * 2 : dataList.size()); i++) {
//                            TargetBaseData data = dataList.get(i);
//                            Map<String, Object> sub = new HashMap<>(7);
//                            sub.put("id", data.getTargetId());
//                            sub.put("grade", "");
//                            sub.put("targetName", data.getTargetName());
//                            sub.put("geographic", data.getCountry());
//                            sub.put("score", data.getIndexValue());
//                            sub.put("degree", StringUtils.isNotBlank(data.getRisk()) ? data.getRisk() : "无");
//                            subList.add(sub);
//                        }
//                        main.put("children", subList);
//                        resultList.add(main);
//                    }
//                }

//                {
//                    if (dataList.size() > length * 2) {
//                        Map<String, Object> main = new HashMap<>(7);
//                        List<Map<String, Object>> subList = new ArrayList<>();
//                        main.put("id", 3);
//                        main.put("grade", "关注");
//                        main.put("targetName", "");
//                        main.put("geographic", "");
//                        main.put("score", "");
//                        main.put("degree", "");
//                        for (int i = length * 2; i < dataList.size(); i++) {
//                            TargetBaseData data = dataList.get(i);
//                            Map<String, Object> sub = new HashMap<>(7);
//                            sub.put("id", data.getTargetId());
//                            sub.put("grade", "");
//                            sub.put("targetName", data.getTargetName());
//                            sub.put("geographic", data.getCountry());
//                            sub.put("score", data.getIndexValue());
//                            sub.put("degree", StringUtils.isNotBlank(data.getRisk()) ? data.getRisk() : "无");
//                            subList.add(sub);
//                        }
//                        main.put("children", subList);
//                        resultList.add(main);
//                    }
//                }
                String grade = null;
                Map<String, Object> main = new HashMap<>();
                Map<String, Object> sub = new HashMap<>();
                List<Map<String, Object>> subList = new ArrayList<>();
                int num = 1;
                for (TargetBaseData data : dataList) {
                    if (null == grade || !grade.equals(data.getGrade())) {
                        if (null != grade && !grade.equals(data.getGrade())) {
                            main.put("children", sortSystemTarget(sysId, grade, subList));
                            resultList.add(main);
                            subList = new ArrayList<>();
                        }
                        main = new HashMap<>(7);
                        main.put("id", num);
                        if ("一级".equals(data.getGrade())) {
                            main.put("grade", "跟瞄");
                        } else if ("二级".equals(data.getGrade())) {
                            main.put("grade", "监视");
                        } else {
                            main.put("grade", "关注");
                        }
                        main.put("targetName", "");
                        main.put("geographic", "");
                        main.put("score", "");
                        main.put("degree", "");
                        main.put("targetMeans", "");
                        grade = data.getGrade();
                        num++;
                    }
                    sub = new HashMap<>(7);
                    sub.put("id", data.getTargetId());
                    sub.put("grade", "");
                    sub.put("targetName", data.getTargetName());
                    sub.put("geographic", data.getCountry());
                    sub.put("score", data.getIndexValue());
                    sub.put("degree", StringUtils.isNotBlank(data.getRisk()) ? data.getRisk() : "无");
                    sub.put("targetMeans", redisUseService.getTargetMeans(data.getTargetId()));
                    subList.add(sub);
                }
                main.put("children", sortSystemTarget(sysId, grade, subList));
                resultList.add(main);
            }
        }
        return resultList;
    }

    private List<Map<String, Object>> sortSystemTarget(String sysId, String grade, List<Map<String, Object>> subList) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(subList)) {
            String redisKey = "SYSTEM_SORT_GRADE_" + grade + "_" + sysId;
            getSortList(redisKey, subList, resultList, "id");
        }
        return resultList;
    }

    private void getSortList(String redisKey, List<Map<String, Object>> subList, List<Map<String, Object>> resultList, String idName) {
        long size = redisUtil.lGetListSize(redisKey);
        List<Object> list = new ArrayList<>();
        if (0 == size) {
            for (Map<String, Object> map : subList) {
                list.add(map.get(idName));
            }
            resultList.addAll(subList);
        } else {
            list = redisUtil.lGet(redisKey, 0, -1);
            sorts(resultList, subList, list, idName);
        }
        redisUtil.del(redisKey);
        redisUtil.lSet(redisKey, list);
    }

    private void sorts(List<Map<String, Object>> resultList, List<Map<String, Object>> subList, List<Object> list, String idName) {
        for (Object id : list) {
            Map<String, Object> m = null;
            for (Map<String, Object> map : subList) {
                if (id.toString().equals(map.get(idName).toString())) {
                    resultList.add(map);
                    m = map;
                    break;
                }
            }
            if (ObjectUtil.isNotEmpty(m)) {
                subList.remove(m);
            }
        }
        if (CollectionUtil.isNotEmpty(subList)) {
            for (Map<String, Object> map : subList) {
                resultList.add(map);
            }
        }
        list = new ArrayList<>();
        for (Map<String, Object> map : resultList) {
            list.add(map.get(idName));
        }
    }

    @Override
    public Result upOrDown(String sysId, String targetId, int type) {
        String grade = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "grade").toString();
        String redisKey = "SYSTEM_SORT_GRADE_" + grade + "_" + sysId;
        upDown(redisKey, targetId, type);
        return ResultUtil.success();
    }

    private void upDown(String redisKey, String targetId, int type) {
        List<Object> list = redisUtil.lGet(redisKey, 0, -1);
        for (int i = 0; i < list.size(); i++) {
            String id = list.get(i).toString();
            if (id.equals(targetId)) {
                if (i == 0 && 1 == type) {
                    break;
                } else if (i == list.size() - 1 && 2 == type) {
                    break;
                } else {
                    moveUpOrDown(list, i, id, type);
                    break;
                }
            }
        }
        redisUtil.del(redisKey);
        redisUtil.lSet(redisKey, list);
    }

    private void moveUpOrDown(List<Object> list, int sign, String targetId, int type) {
        List<Object> middle = new ArrayList<>();
        int j = 0;
        if (1 == type) {
            for (int i = sign - 1; i < list.size(); i++) {
                if (i == sign) {
                    continue;
                }
                middle.add(list.get(i));
            }
            list.set(sign - 1, targetId);
            for (int i = sign; i < list.size(); i++) {
                list.set(i, middle.get(j));
                j++;
            }
        } else {
            for (int i = 0; i <= sign + 1; i++) {
                if (i == sign) {
                    continue;
                }
                middle.add(list.get(i));
            }
            list.set(sign + 1, targetId);
            for (int i = 0; i <= sign; i++) {
                list.set(i, middle.get(j));
                j++;
            }
        }
    }

    @Override
    public Map<String, Object> getSystemsTypeIndex(String sysId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<String> xAxle = new ArrayList<>();
        List<Double> yAxle = new ArrayList<>();
        List<TypeIndexVo> indexVos = targetTypeMapper.getSystemsTypeIndex(sysId);
        if (CollectionUtil.isNotEmpty(indexVos)) {
            Map<String, Object> map;
            for (int i = 0; i < indexVos.size(); i++) {
                map = new HashMap<>();
                TypeIndexVo typeIndexVo = indexVos.get(i);
                map.put("number", i + 1);
                map.put("typeName", typeIndexVo.getTypeName());
                map.put("grade", typeIndexVo.getIndexValue());
                dataList.add(map);
                xAxle.add(typeIndexVo.getTypeName());
                yAxle.add(typeIndexVo.getIndexValue());
            }
        }
        resultMap.put("dataList", dataList);
        resultMap.put("xAxle", xAxle);
        resultMap.put("yAxle", yAxle);
        return resultMap;
    }

    @Override
    public Result addRangeType(JSONObject json) {
        String id = json.getString("id");
        String rangeType = json.getString("rangeType");
        String rangeName = json.getString("rangeName");
        String color = json.getString("color");
        RangeType type = new RangeType();
        type.setName(rangeName);
        type.setRangeType(rangeType);
        type.setColor(color);
        if ("0".equals(id)) {
            rangeTypeMapper.insert(type);
        } else {
            type.setId(id);
            rangeTypeMapper.updateById(type);
        }
        redisUseService.updateRangeType(type.getId(), JSON.toJSONString(type));
        Map<String, Object> map = new HashMap<>();
        map.put("id", type.getId());
        return ResultUtil.success(map);
    }

    @Override
    public Result deleteRangeType(JSONObject json) {
        String id = json.getString("id");
        rangeTypeMapper.deleteById(id);
        redisUseService.deleteRangeType(id);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result selectRangeType(JSONObject json) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Boolean isPull = json.getBoolean("isPull");
        List<RangeType> rangeTypes = rangeTypeMapper.selectList(null);
        if (CollectionUtil.isNotEmpty(rangeTypes)) {
            Map<String, Object> map;
            for (RangeType rangeType : rangeTypes) {
                map = new HashMap<>();
                if (null != isPull && isPull) {
                    map.put("value", rangeType.getId());
                    map.put("label", rangeType.getName());
                } else {
                    map.put("id", rangeType.getId());
                    map.put("rangeName", rangeType.getName());
                    map.put("rangeType", rangeType.getRangeType());
                    map.put("color", rangeType.getColor());
                }
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result selectSystemsAnalysisData(String sysId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("sysId", sysId);
        resultMap.put("intention", "");
        resultMap.put("powerList", ListUtil.empty());
        if (redisUtil.hHasKey("SYSTEMS_ANALYSIS_DATA", sysId)) {
            SystemsIndexPowerVo indexPowerVo = JSONObject.parseObject(redisUtil.hget("SYSTEMS_ANALYSIS_DATA", sysId).toString(), SystemsIndexPowerVo.class);
            resultMap.put("intention", indexPowerVo.getIntention());
            resultMap.put("powerList", indexPowerVo.getPowerList());
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result selectSystemsPowerPull(String sysId) {
        Set<String> targetIds = redisUseService.selectSystemsTargetIds(sysId);
        //查询目标的一级指标名称
        List<Map<String, Object>> resutList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(targetIds)) {
            Set<String> set = new HashSet<>();
            List<SystemIndex> indices = systemIndexService.lambdaQuery().in(SystemIndex::getRedId, targetIds).eq(SystemIndex::getLevel, "1").eq(SystemIndex::getType, "ununder").list();
            if (CollectionUtil.isNotEmpty(indices)) {
                for (SystemIndex index : indices) {
                    set.add(index.getIndicatorName());
                }
            }
            for (String s : set) {
                Map<String, Object> map = new HashMap<>();
                map.put("label", s);
                map.put("value", s);
                resutList.add(map);
            }
        }
        return ResultUtil.success(resutList);
    }

    @Override
    public Result restartSystemsAnalysis(String sysId) {
        redisUtil.hdel("SYSTEMS_ANALYSIS_DATA", sysId);
        redisUtil.del(
                "SYSTEM_SORT_POWER_TARGET_DELETE_" + sysId,
                "SYSTEM_SORT_POWER_TARGET_" + sysId,
                "SYSTEM_SORT_CHOOSE_TARGET_LIST_" + sysId,
                "SYSTEM_SORT_CHOOSE_TARGET_LIST_SORT_" + sysId
        );
        return ResultUtil.success();
    }

    @Override
    public Result selectAysMBList(SystemsIndexPowerVo powerVo) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        redisUtil.hset("SYSTEMS_ANALYSIS_DATA", powerVo.getSysId(), JSON.toJSONString(powerVo));
        Set<String> targetIds = redisUseService.selectSystemsTargetIds(powerVo.getSysId());
        if (CollectionUtil.isNotEmpty(targetIds)) {
            if (CollectionUtil.isNotEmpty(powerVo.getPowerList())) {
                Map<String, Double> poserMap = new HashMap<>();
                List<String> powerList = new ArrayList<>();
                for (PowerVo vo : powerVo.getPowerList()) {
                    if (StringUtils.isNotBlank(vo.getPowerId())) {
                        powerList.add(vo.getPowerId());
                        poserMap.put(vo.getPowerId(), vo.getIndexValue());
                    }
                }
                if (CollectionUtil.isNotEmpty(powerList)) {
                    List<SystemIndex> indices = systemIndexService.lambdaQuery()
                            .in(SystemIndex::getIndicatorName, powerList)
                            .in(SystemIndex::getRedId, targetIds)
                            .eq(SystemIndex::getLevel, "1")
                            .eq(SystemIndex::getType, "ununder")
                            .list();
                    targetIds = new HashSet<>();
                    if (CollectionUtil.isNotEmpty(indices)) {
                        for (SystemIndex index : indices) {
                            targetIds.add(index.getRedId());
                        }
                        //指标筛选
                        Map<Object, Object> index = new HashMap<>();
                        getTotal(targetIds, 0D, index);
                        Set newTarget = new HashSet();
                        for (String powerId : poserMap.keySet()) {
                            for (String targetId : targetIds) {
                                String redisName = RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1;
                                if (redisUtil.hHasKey(redisName, powerId)) {
                                    double levelValue = redisUseService.getIndexLevelValue(targetId, "1", powerId);
                                    if (levelValue > 0) {
                                        double total = FileElseUtil.getObjectToDouble(index.get(powerId));
                                        Double aDouble = poserMap.get(powerId);
                                        newTarget.add(targetId);
                                        if ((levelValue / total * 100) <= aDouble) {
                                            break;
                                        }
                                    } else {
                                        newTarget.add(targetId);
                                    }
                                }
                            }
                        }
                        targetIds = newTarget;
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(targetIds)) {
                List<Map<String, Object>> subList = new ArrayList<>();
                List<TargetBaseData> baseData = targetBaseDataService
                        .lambdaQuery()
                        .in(TargetBaseData::getTargetId, targetIds)
                        .orderByDesc(TargetBaseData::getIndexValue)
                        .list();
                Map<String, Object> map;
                for (TargetBaseData base : baseData) {
                    if (redisUtil.sHasKey("SYSTEM_SORT_POWER_TARGET_DELETE_" + powerVo.getSysId(), base.getTargetId())) {
                        continue;
                    }
                    if (redisUtil.sHasKey("SYSTEM_SORT_CHOOSE_TARGET_LIST_" + powerVo.getSysId(), base.getTargetId())) {
                        continue;
                    }
                    map = new HashMap<>();
                    map.put("targetId", base.getTargetId());
                    map.put("targetName", base.getTargetName());
                    map.put("country", base.getCountry());
                    map.put("damage", "重度毁伤");
                    map.put("indexVale", base.getIndexValue());
                    map.put("grade", base.getGrade());
                    subList.add(map);
                }
                if (CollectionUtil.isNotEmpty(subList)) {
                    String redisKey = "SYSTEM_SORT_POWER_TARGET_" + powerVo.getSysId();
                    getSortList(redisKey, subList, resultList, "targetId");
                }
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result aysMBSort(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        Integer type = json.getInteger("type");
        String redisKey = "SYSTEM_SORT_POWER_TARGET_" + sysId;
        upDown(redisKey, targetId, type);
        if (redisUtil.hHasKey("SYSTEMS_ANALYSIS_DATA", sysId)) {
            SystemsIndexPowerVo indexPowerVo = JSONObject.parseObject(redisUtil.hget("SYSTEMS_ANALYSIS_DATA", sysId).toString(), SystemsIndexPowerVo.class);
            return selectAysMBList(indexPowerVo);
        } else {
            SystemsIndexPowerVo indexPowerVo = new SystemsIndexPowerVo();
            indexPowerVo.setSysId(sysId);
            return selectAysMBList(indexPowerVo);
        }
    }

    @Override
    public Result aysMBDelete(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        String redisKey = "SYSTEM_SORT_POWER_TARGET_DELETE_" + sysId;
        redisUtil.sSet(redisKey, targetId);
        if (redisUtil.hHasKey("SYSTEMS_ANALYSIS_DATA", sysId)) {
            SystemsIndexPowerVo indexPowerVo = JSONObject.parseObject(redisUtil.hget("SYSTEMS_ANALYSIS_DATA", sysId).toString(), SystemsIndexPowerVo.class);
            return selectAysMBList(indexPowerVo);
        } else {
            SystemsIndexPowerVo indexPowerVo = new SystemsIndexPowerVo();
            indexPowerVo.setSysId(sysId);
            return selectAysMBList(indexPowerVo);
        }
    }

    @Override
    public Result aysMBMove(JSONObject json) {
        String sysId = json.getString("sysId");
        JSONArray targetIds = json.getJSONArray("targetList");
        String redisKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_" + sysId;
        for (Object targetId : targetIds) {
            redisUtil.sSet(redisKey, targetId);
        }
        if (redisUtil.hHasKey("SYSTEMS_ANALYSIS_DATA", sysId)) {
            SystemsIndexPowerVo indexPowerVo = JSONObject.parseObject(redisUtil.hget("SYSTEMS_ANALYSIS_DATA", sysId).toString(), SystemsIndexPowerVo.class);
            return selectAysMBList(indexPowerVo);
        } else {
            SystemsIndexPowerVo indexPowerVo = new SystemsIndexPowerVo();
            indexPowerVo.setSysId(sysId);
            return selectAysMBList(indexPowerVo);
        }
    }

    @Override
    public Result aysMBChooseList(JSONObject json) {
        String sysId = json.getString("sysId");
        List<Map<String, Object>> resultList = new ArrayList<>();
        String redisKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_" + sysId;
        if (redisUtil.hasKey(redisKey)) {
            Set<Object> ids = redisUtil.sGet(redisKey);
            List<Map<String, Object>> subList = new ArrayList<>();
            List<TargetBaseData> baseData = targetBaseDataService.lambdaQuery().in(TargetBaseData::getTargetId, ids).orderByDesc(TargetBaseData::getIndexValue).list();
            Map<String, Object> map;
            for (TargetBaseData base : baseData) {
                map = new HashMap<>();
                map.put("targetId", base.getTargetId());
                map.put("targetName", base.getTargetName());
                map.put("country", base.getCountry());
                map.put("damage", "重度毁伤");
                map.put("indexVale", base.getIndexValue());
                map.put("grade", base.getGrade());
                subList.add(map);
            }
            if (CollectionUtil.isNotEmpty(subList)) {
                String redisSortKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_SORT_" + sysId;
                getSortList(redisSortKey, subList, resultList, "targetId");
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result aysMBChooseSort(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        Integer type = json.getInteger("type");
        String redisKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_SORT_" + sysId;
        upDown(redisKey, targetId, type);
        return aysMBChooseList(json);
    }

    @Override
    public Result aysMBChooseDelete(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        String redisKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_" + sysId;
        redisUtil.setRemove(redisKey, targetId);
        return aysMBChooseList(json);
    }

    @Override
    public Result hitAnalysis(String sysId) {
        Map<String, Object> resultMap = new HashMap<>();
        SystemsMaster master = systemsMasterMapper.findSystemsMasterById(sysId);
        resultMap.put("sysName", master.getSystemsName());
        resultMap.put("total", "0%");
        resultMap.put("powerList", ListUtil.empty());
        resultMap.put("targetList", ListUtil.empty());
        String redisKey = "SYSTEM_SORT_CHOOSE_TARGET_LIST_" + sysId;
        if (redisUtil.hasKey(redisKey)) {
            Set<String> targetIds = redisUseService.selectSystemsTargetIds(sysId);
            double total = 0D;
            double subValue = 0D;
            Map<Object, Object> main = new HashMap<>();
            Map<Object, Object> sub = new HashMap<>();
            //体系所有指标总分
            total = getTotal(targetIds, total, main);
            //选中指标得分
            Set<Object> objects = redisUtil.sGet(redisKey);
            subValue = getTotal(objects, subValue, sub);
            resultMap.put("total", (total > 0 ? FileElseUtil.getObjectToDouble(subValue / total * 100) : 0));
            if (CollectionUtil.isNotEmpty(sub)) {
                List<Map<String, Object>> powerList = new ArrayList<>();
                List<Map<String, Object>> targetList = new ArrayList<>();
                for (Object id : sub.keySet()) {
                    //得分计算
                    Map<String, Object> map = new HashMap<>();
                    map.put("label", id);
                    double m = FileElseUtil.getObjectToDouble(main.get(id));
                    double s = FileElseUtil.getObjectToDouble(sub.get(id));
                    map.put("value", (m > 0 ? FileElseUtil.getObjectToDouble(s / m * 100) : 0));
                    powerList.add(map);
                    //目标信息
                    Map<String, Object> tMap = new HashMap<>();
                    tMap.put("position", redisUseService.getViewPosition(id.toString()));
                    targetList.add(tMap);
                }
                resultMap.put("powerList", powerList);
            }
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result saveAnalysis(SystemsTargetListVo systemsTargetListVo) {
        if (redisUtil.hHasKey("SYSTEMS_ANALYSIS_DATA", systemsTargetListVo.getSysId())) {
            SystemsIndexPowerVo indexPowerVo = JSONObject.parseObject(redisUtil.hget("SYSTEMS_ANALYSIS_DATA", systemsTargetListVo.getSysId()).toString(), SystemsIndexPowerVo.class);

            SceneSystemsList sceneSystemsList = new SceneSystemsList();
            sceneSystemsList.setSysId(systemsTargetListVo.getSysId());
            sceneSystemsList.setIntention(StringUtils.isNotBlank(indexPowerVo.getIntention()) ? indexPowerVo.getIntention() : "未定义意图");
            sceneSystemsListService.save(sceneSystemsList);

            if (CollectionUtil.isNotEmpty(indexPowerVo.getPowerList())) {
                List<SceneIndexList> sceneIndexLists = new ArrayList<>();
                for (PowerVo powerVo : indexPowerVo.getPowerList()) {
                    SceneIndexList sceneIndexList = new SceneIndexList();
                    sceneIndexList.setSceneId(sceneSystemsList.getId());
                    sceneIndexList.setIndexName(powerVo.getPowerId());
                    sceneIndexList.setIndexValue(powerVo.getIndexValue());
                    sceneIndexLists.add(sceneIndexList);
                }
                sceneIndexListService.saveBatch(sceneIndexLists);
            }

            if (CollectionUtil.isNotEmpty(systemsTargetListVo.getTargetList())) {
                List<SceneTargetList> sceneTargetLists = new ArrayList<>();
                for (TargetList targetList : systemsTargetListVo.getTargetList()) {
                    SceneTargetList sceneTargetList = new SceneTargetList();
                    sceneTargetList.setSceneId(sceneSystemsList.getId());
                    sceneTargetList.setTargetId(targetList.getTargetId());
                    sceneTargetList.setDamage(targetList.getDamage());
                    sceneTargetLists.add(sceneTargetList);
                }
                sceneTargetListService.saveBatch(sceneTargetLists);
            }
        }
        return ResultUtil.success();
    }

    @Override
    public Result selectSceneList() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<SceneSystemsList> systemsLists = sceneSystemsListService.selectSceneList();
        if (CollectionUtil.isNotEmpty(systemsLists)) {
            Map<String, Object> map;
            Map<String, Object> sub;
            for (SceneSystemsList systemsList : systemsLists) {
                map = new HashMap<>();
                map.put("sceneId", systemsList.getId());
                map.put("intention", "【" + systemsList.getSysName() + "】" + systemsList.getIntention());
                map.put("sysId", systemsList.getSysId());
                map.put("targetId", "");
                List<Map<String, Object>> subList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(systemsList.getTargetLists())) {
                    for (SceneTargetList targetList : systemsList.getTargetLists()) {
                        sub = new HashMap<>();
                        sub.put("sceneId", systemsList.getId());
                        sub.put("intention", targetList.getTargetName());
                        sub.put("sysId", systemsList.getSysId());
                        sub.put("targetId", targetList.getTargetId());
                        subList.add(sub);
                    }
                }
                map.put("children", subList);
                list.add(map);
            }
        }
        return ResultUtil.success(list);
    }

    @Override
    public Result selectSceneData(String sceneId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("indexList", ListUtil.empty());
        resultMap.put("targetList", ListUtil.empty());
        if (StringUtils.isBlank(sceneId)) {
            return ResultUtil.success(resultMap);
        }
        //指标
        List<SceneIndexList> indexLists = sceneIndexListService.lambdaQuery().eq(SceneIndexList::getSceneId, sceneId).list();
        if (CollectionUtil.isNotEmpty(indexLists)) {
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map;
            for (SceneIndexList index : indexLists) {
                map = new HashMap<>();
                map.put("sceneId", sceneId);
                map.put("powerId", index.getId());
                map.put("powerName", index.getIndexName());
                map.put("powerValue", index.getIndexValue());
                list.add(map);
            }
            resultMap.put("indexList", list);
        }
        //目标
        List<SceneTargetList> targetLists = sceneTargetListService.selectTargetList(sceneId);
        if (CollectionUtil.isNotEmpty(targetLists)) {
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map;
            for (SceneTargetList targetList : targetLists) {
                map = new HashMap<>();
                map.put("sceneId", sceneId);
                map.put("targetId", targetList.getTargetId());
                map.put("subId", "");
                map.put("targetName", targetList.getTargetName());
                map.put("damage", targetList.getDamage());
                map.put("missile", "");
                map.put("payload", "");
                map.put("elastance", "");
                map.put("type", 1);
                map.put("targetList", FileElseUtil.getObjectToList(targetList.getTargetList()));
                map.put("missileList", FileElseUtil.getObjectToList(targetList.getMissileList()));
                map.put("payloadList", FileElseUtil.getObjectToList(targetList.getPayloadList()));
                List<Map<String, Object>> subList = new ArrayList<>();
                //子目标
                int index = 0;
                if (CollectionUtil.isNotEmpty(targetList.getSubList())) {
                    Map<String, Object> sub;
                    for (SceneSubList sceneSubList : targetList.getSubList()) {
                        sub = new HashMap<>();
                        sub.put("sceneId", sceneId);
                        sub.put("targetId", sceneSubList.getTargetId());
                        sub.put("subId", sceneSubList.getSubId());
                        sub.put("targetName", "");
                        sub.put("index", index);
                        sub.put("damage", FileElseUtil.getObjectToString(sceneSubList.getDamage()));
                        sub.put("missile", FileElseUtil.getObjectToString(sceneSubList.getMissile()));
                        sub.put("payload", FileElseUtil.getObjectToString(sceneSubList.getPayload()));
                        sub.put("elastance", FileElseUtil.getObjectToInt(sceneSubList.getElastance()));
                        sub.put("type", 2);
                        sub.put("targetList", FileElseUtil.getObjectToList(sceneSubList.getTargetList()));
                        sub.put("missileList", FileElseUtil.getObjectToList(sceneSubList.getMissileList()));
                        sub.put("payloadList", FileElseUtil.getObjectToList(sceneSubList.getPayloadList()));
                        subList.add(sub);
                        index++;
                    }
                }
                map.put("children", subList);
                list.add(map);
            }
            resultMap.put("targetList", list);
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result updateSceneTarget(JSONObject json) {
        String sceneId = json.getString("sceneId");
        String targetId = json.getString("targetId");
        String damage = json.getString("damage");
        sceneTargetListService.lambdaUpdate().set(SceneTargetList::getDamage, damage).eq(SceneTargetList::getSceneId, sceneId).eq(SceneTargetList::getTargetId, targetId).update();
        return ResultUtil.success();
    }

    @Override
    public Result deleteSceneTarget(JSONObject json) {
        String sceneId = json.getString("sceneId");
        String targetId = json.getString("targetId");
        sceneTargetListService.lambdaUpdate().eq(SceneTargetList::getSceneId, sceneId).eq(SceneTargetList::getTargetId, targetId).remove();
        sceneSubListService.lambdaUpdate().eq(SceneSubList::getSceneId, sceneId).eq(SceneSubList::getTargetId, targetId).remove();
        return ResultUtil.success();
    }

    @Override
    public Result selectSceneSubPull(String targetId) {
        List<Map<String, Object>> subList = new ArrayList<>();
        if (redisUtil.hasKey(RedisName.TARGET_SUB_RELATION_LIST + "_" + targetId)) {
            Set<Object> subSet = redisUtil.sGet(RedisName.TARGET_SUB_RELATION_LIST + "_" + targetId);
            Map<String, Object> sub;
            for (Object id : subSet) {
                sub = new HashMap<>();
                sub.put("label", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName")));
                sub.put("value", id);
                subList.add(sub);
            }
        }
        return ResultUtil.success(subList);
    }

    @Override
    public Result addSceneSub(JSONObject json) {
        String sceneId = json.getString("sceneId");
        String targetId = json.getString("targetId");
        String subId = json.getString("subId");
        String damage = json.getString("damage");
        String missile = json.getString("missile");
        String payload = json.getString("payload");
        String elastance = json.getString("elastance");
        SceneSubList one = sceneSubListService.lambdaQuery().eq(SceneSubList::getSceneId, sceneId).eq(SceneSubList::getTargetId, targetId).eq(SceneSubList::getSubId, subId).last("LIMIT 1").one();
        if (ObjectUtil.isEmpty(one)) {
            one = new SceneSubList();
        }
        one.setSceneId(sceneId);
        one.setTargetId(targetId);
        one.setSubId(subId);
        one.setDamage(damage);
        one.setDamage(missile);
        one.setDamage(payload);
        one.setDamage(elastance);
        sceneSubListService.saveOrUpdate(one);
        return ResultUtil.success();
    }

    @Override
    public Result deleteSceneSub(JSONObject json) {
        String sceneId = json.getString("sceneId");
        String targetId = json.getString("targetId");
        String subId = json.getString("subId");
        sceneSubListService.lambdaUpdate().eq(SceneSubList::getSceneId, sceneId).eq(SceneSubList::getTargetId, targetId).eq(SceneSubList::getSubId, subId).remove();
        return ResultUtil.success();
    }

    @Override
    public Result saveIndexList(JSONObject json) {
        String sceneId = json.getString("sceneId");
        JSONArray indexList = json.getJSONArray("indexList");
        JSONArray targetList = json.getJSONArray("targetList");
        sceneIndexListService.lambdaUpdate().eq(SceneIndexList::getSceneId, sceneId).remove();
        sceneTargetListService.lambdaUpdate().eq(SceneTargetList::getSceneId, sceneId).remove();
        sceneSubListService.lambdaUpdate().eq(SceneSubList::getSceneId, sceneId).remove();
        if (CollectionUtil.isNotEmpty(indexList)) {
            List<SceneIndexList> indexLists = new ArrayList<>();
            for (int i = 0; i < indexList.size(); i++) {
                JSONObject index = indexList.getJSONObject(i);
                SceneIndexList sceneIndexList = new SceneIndexList();
                sceneIndexList.setSceneId(sceneId);
                sceneIndexList.setIndexName(index.getString("powerName"));
                sceneIndexList.setIndexValue(FileElseUtil.getObjectToDouble(index.getString("powerValue")));
                indexLists.add(sceneIndexList);
            }
            sceneIndexListService.saveBatch(indexLists);
        }
        if (CollectionUtil.isNotEmpty(targetList)) {
            List<SceneTargetList> targets = new ArrayList<>();
            List<SceneSubList> subs = new ArrayList<>();
            for (int i = 0; i < targetList.size(); i++) {
                JSONObject t = targetList.getJSONObject(i);
                if (StringUtils.isBlank(t.getString("targetId"))) {
                    continue;
                }
                SceneTargetList td = new SceneTargetList();
                td.setSceneId(t.getString("sceneId"));
                td.setTargetId(t.getString("targetId"));
                td.setDamage(t.getString("damage"));
                td.setTargetList(t.getJSONArray("targetList").toJSONString());
                td.setMissileList(t.getJSONArray("missileList").toJSONString());
                td.setPayloadList(t.getJSONArray("payloadList").toJSONString());
                targets.add(td);
                if (CollectionUtil.isNotEmpty(t.getJSONArray("children"))) {
                    JSONArray children = t.getJSONArray("children");
                    for (int j = 0; j < children.size(); j++) {
                        JSONObject s = children.getJSONObject(j);
                        if (StringUtils.isBlank(s.getString("subId"))) {
                            continue;
                        }
                        SceneSubList sd = new SceneSubList();
                        sd.setSceneId(s.getString("sceneId"));
                        sd.setTargetId(s.getString("targetId"));
                        sd.setSubId(s.getString("subId"));
                        sd.setDamage(s.getString("damage"));
                        sd.setMissile(s.getString("missile"));
                        sd.setPayload(s.getString("payload"));
                        sd.setElastance(s.getString("elastance"));
                        sd.setTargetList(s.getJSONArray("targetList").toJSONString());
                        sd.setMissileList(s.getJSONArray("missileList").toJSONString());
                        sd.setPayloadList(s.getJSONArray("payloadList").toJSONString());
                        subs.add(sd);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(targets)) {
                sceneTargetListService.saveBatch(targets);
            }
            if (CollectionUtil.isNotEmpty(subs)) {
                sceneSubListService.saveBatch(subs);
            }
        }
        return ResultUtil.success();
    }

    @Override
    public Result missilePull() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> missileList = sceneSystemsListService.getMissileList();
        if (CollectionUtil.isNotEmpty(missileList)) {
            for (Map<String, Object> map : missileList) {
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result payloadPull(String missileId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> weaponList = sceneSystemsListService.getWeaponList(missileId);
        if (CollectionUtil.isNotEmpty(weaponList)) {
            for (Map<String, Object> map : weaponList) {
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result exportExcel(String sceneId) {
        if (StringUtils.isNotBlank(sceneId)) {
            String url = "/file/" + UUID.randomUUID().toString() + "/体系分析.xlsx";
            String fileUrl = keyWordSystem.getFILE_URL() + url;
            FileUtil.mkParentDirs(fileUrl);
            // 创建一个新的工作簿
            Workbook workbook = new XSSFWorkbook();

            // 创建一个工作表
            Sheet sheet = workbook.createSheet("分析");

            //设置宽度
            sheet.setColumnWidth(0, 20 * 256);
            sheet.setColumnWidth(1, 20 * 256);
            sheet.setColumnWidth(2, 20 * 256);
            sheet.setColumnWidth(3, 20 * 256);
            sheet.setColumnWidth(4, 20 * 256);

            int rowNum = 0;
            SceneSystemsList sceneSystemsList = sceneSystemsListService.getById(sceneId);

            {
                // 创建行（0基索引）
                Row row = sheet.createRow(rowNum);

                //头部信息
                Cell cell = row.createCell(0);
                cell.setCellValue("意图");
                cell = row.createCell(1);
                cell.setCellValue(sceneSystemsList.getIntention());

                //合并单元格
                CellRangeAddress addresses = new CellRangeAddress(rowNum, rowNum, 1, 4);
                sheet.addMergedRegion(addresses);

                rowNum++;
            }

            List<SceneIndexList> sceneIndexLists = sceneIndexListService.lambdaQuery().eq(SceneIndexList::getSceneId, sceneId).list();

            if (CollectionUtil.isNotEmpty(sceneIndexLists)) {
                // 创建行（0基索引）
                Row row = sheet.createRow(rowNum);
                //头部信息
                Cell cell = row.createCell(0);
                cell.setCellValue("指标能力");
                cell = row.createCell(1);
                cell.setCellValue("下降数值");

                //合并单元格
                CellRangeAddress addresses = new CellRangeAddress(rowNum, rowNum, 1, 4);
                sheet.addMergedRegion(addresses);

                rowNum++;
                for (SceneIndexList indexList : sceneIndexLists) {
                    row = sheet.createRow(rowNum);
                    //头部信息
                    cell = row.createCell(0);
                    cell.setCellValue(indexList.getIndexName());
                    cell = row.createCell(1);
                    cell.setCellValue(FileElseUtil.getObjectToDouble(indexList.getIndexValue()));

                    //合并单元格
                    addresses = new CellRangeAddress(rowNum, rowNum, 1, 4);
                    sheet.addMergedRegion(addresses);

                    rowNum++;
                }
            }

            List<SceneTargetList> targetLists = sceneTargetListService.selectTargetList(sceneId);
            if (CollectionUtil.isNotEmpty(targetLists)) {
                // 创建行（0基索引）
                Row row = sheet.createRow(rowNum);
                //头部信息
                Cell cell = row.createCell(0);
                cell.setCellValue("目标/子目标名称");
                cell = row.createCell(1);
                cell.setCellValue("毁伤等级");
                cell = row.createCell(2);
                cell.setCellValue("弹型弹种");
                cell = row.createCell(3);
                cell.setCellValue("战斗部");
                cell = row.createCell(4);
                cell.setCellValue("弹量");
                rowNum++;
                for (SceneTargetList targetList : targetLists) {
                    row = sheet.createRow(rowNum);
                    //头部信息
                    cell = row.createCell(0);
                    cell.setCellValue(targetList.getTargetName());
                    cell = row.createCell(1);
                    cell.setCellValue(targetList.getDamage());
                    cell = row.createCell(2);
                    cell.setCellValue("");
                    cell = row.createCell(3);
                    cell.setCellValue("");
                    cell = row.createCell(4);
                    cell.setCellValue("");
                    rowNum++;
                    for (SceneSubList sceneSubList : targetList.getSubList()) {
                        row = sheet.createRow(rowNum);
                        //头部信息
                        cell = row.createCell(0);
                        cell.setCellValue(FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + sceneSubList.getSubId(), "targetName")));
                        cell = row.createCell(1);
                        cell.setCellValue(sceneSubList.getDamage());
                        cell = row.createCell(2);
                        cell.setCellValue(FileElseUtil.getObjectToString(sceneSubList.getMissileName()));
                        cell = row.createCell(3);
                        cell.setCellValue(FileElseUtil.getObjectToString(sceneSubList.getPayloadName()));
                        cell = row.createCell(4);
                        cell.setCellValue(FileElseUtil.getObjectToInt(sceneSubList.getElastance()));
                        rowNum++;
                    }
                }
            }

            // 获取或创建列的样式
            CellStyle wrapAndCenterStyle = createWrappedAndCenteredCellStyle(workbook);

            // 假设我们想要设置A列（列索引为0）
            int columnIndexToFormat = 5;
            int maxRows = rowNum - 1;

            // 遍历列中的所有单元格并应用样式
            for (int rowIndex = 0; rowIndex <= maxRows; rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    row = sheet.createRow(rowIndex);
                }
                for (int i = 0; i < columnIndexToFormat; i++) {
                    Cell cell = row.getCell(i);
                    if (cell == null) {
                        cell = row.createCell(i);
                    }
                    cell.setCellStyle(wrapAndCenterStyle);
                }
            }

            // 写入到文件
            try (FileOutputStream outputStream = new FileOutputStream(fileUrl)) {
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 清理资源
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("fileUrl", keyWordSystem.getSERVER_URL() + url);
            return ResultUtil.success(resultMap);
        }
        return ResultUtil.error(500, "请选择需要导出的场景");
    }

    @Override
    public Result getHitTarget() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> hitTarget = sceneSystemsListService.getHitTarget();
        if (CollectionUtil.isNotEmpty(hitTarget)) {
            Map<String, Object> m;
            for (Map<String, Object> map : hitTarget) {
                if (ObjectUtil.isNotEmpty(map.get("lon")) && ObjectUtil.isNotEmpty(map.get("lat"))) {
                    m = new HashMap<>();
                    m.put("targetName", map.get("targetName"));
                    double lon = FileElseUtil.getStringTransitionDouble(map.get("lon").toString());
                    if (lon == 0) {
                        continue;
                    }
                    double lat = FileElseUtil.getStringTransitionDouble(map.get("lat").toString());
                    if (lat == 0) {
                        continue;
                    }
                    m.put("position", Arrays.asList(lon, lat, 0));
                    list.add(m);
                }
            }
        }
        return ResultUtil.success(list);
    }

    @Override
    public Result  getSystemsTargetStaticAnalyse(String sysId) {
        //重要
        int important = 0;
        //关注
        int attention = 0;
        //一般
        int ordinary = 0;
        List<Object> table = new ArrayList<>();
        //查询体系下所有的目标
        List<String> targetList = redisUseService.getSystemsTargetList(sysId);
        if (CollectionUtil.isNotEmpty(targetList)) {
            //获取目标指标头部数据
            List<String> header = new ArrayList<>();
            Set<String> s = new HashSet<>();
            header.add("目标");
            for (String targetId : targetList) {
                if (redisUtil.hasKey(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1)) {
                    Map<Object, Object> indexMap = redisUtil.hmget(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1);
                    for (Object key : indexMap.keySet()) {
                        s.add(FileElseUtil.getObjectToString(key));
                    }
                }
                //获取目标等级
                String grade = FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "grade"));
                switch (grade) {
                    case "一级":
                        important++;
                        break;
                    case "二级":
                        attention++;
                        break;
                    case "三级":
                        ordinary++;
                        break;
                    default:
                        break;
                }
            }
            header.addAll(s);
            header.add("分值");
            header.add("排序");
            table.add(header);
            //获取目标实际指标数据
            List<List<Object>> targets = new ArrayList<>();
            for (String targetId : targetList) {
                List<Object> target = new ArrayList<>();
                //目标名称
                target.add(FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
                double total = 0;
                if (header.size() > 3) {
                    if (redisUtil.hasKey(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1)) {
                        for (int i = 1; i < header.size() - 2; i++) {
                            Map<Object, Object> indexMap = redisUtil.hmget(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1);
                            double value = FileElseUtil.getObjectToDouble(indexMap.get(header.get(i)));
                            total+= value;
                            target.add(value);
                        }
                    } else {
                        for (int i = 1; i < header.size() - 2; i++) {
                            target.add(0);
                        }
                    }
                }
                target.add(total);
                targets.add(target);
            }
            //根据目标指标总数大小排序
            if (header.size() > 3) {
                targets.sort(new Comparator<List<Object>>() {
                    @Override
                    public int compare(List<Object> o1, List<Object> o2) {
                        double v1 = FileElseUtil.getObjectToDouble(o1.get(o1.size() - 1));
                        double v2 = FileElseUtil.getObjectToDouble(o2.get(o2.size() - 1));
                        return Double.compare(v2, v1);
                    }
                });
            }
            for (int i = 0; i < targets.size(); i++) {
                List<Object> list = targets.get(i);
                list.add(i + 1);
            }
            table.addAll(targets);
        }
        Map<String, Object> resultMap = new HashMap<>();
        {
            List<Map<String, Object>> chart = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                Map<String, Object> map =  new HashMap<>();
                switch (i) {
                    case 0:
                        map.put("name", "重要");
                        map.put("value", important);
                        break;
                    case 1:
                        map.put("name", "关注");
                        map.put("value", attention);
                        break;
                    case 2:
                        map.put("name", "一般");
                        map.put("value", ordinary);
                        break;
                }
                chart.add(map);
            }
            resultMap.put("chart", chart);
        }
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result getSystemsRulePostureList(String sysId, Integer type) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<SystemsDynamic> dynamics = systemsDynamicService
                .lambdaQuery()
                .eq(SystemsDynamic::getSysId, sysId)
                .eq(SystemsDynamic::getType, type)
                .list();
        dynamics.forEach(data -> {
            Map<String, Object> map = new HashMap<>();
            map.put("stay_id", data.getPostureId());
            map.put("num", data.getNumber());
            map.put("sub_id", data.getTargetId());
            resultList.add(map);
        });
        return ResultUtil.success(resultList);
    }

    @Override
    public Result getSystemsRuleAnalyse(SystemsDynamicVo systemsDynamicVo) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> numMap = new HashMap<>();
        Map<String, Map<String, Double>> valueMap = new HashMap<>();
        //处理停驻列表
        systemsDynamicService.lambdaUpdate()
                .eq(SystemsDynamic::getSysId, systemsDynamicVo.getSysId())
                .eq(SystemsDynamic::getType, 1)
                .remove();
        if (CollectionUtil.isNotEmpty(systemsDynamicVo.getParamList())) {
            List<SystemsDynamic> dynamicList = systemsDynamicVo.getParamList().stream().map(data -> {
                //得分
                if (null != data.getNum() && StringUtils.isNotBlank(data.getStay_id()) && StringUtils.isNotBlank(data.getSub_id())) {
                    Map<String, Double> m = new HashMap<>();
                    if (null != valueMap.get(data.getSub_id())) {
                        m = valueMap.get(data.getSub_id());
                    }
                    String key = redisUseService.getPostureTypeName(data.getStay_id());
                    double value = 0;
                    //图表
                    Integer number = 0;
                    if (null != numMap.get(key)) {
                        number = numMap.get(key);
                    }
                    number += data.getNum();
                    numMap.put(key, number);
                    PostureComputeType computeType = postureComputeTypeService.getById(data.getStay_id());
                    if (ObjectUtil.isNotEmpty(computeType)) {
                        if ("1".equals(computeType.getComputeType())) {
                            JSONObject object = JSONObject.parseObject(computeType.getComputeParam());
                            value = object.getDouble("field") * data.getNum();
                        } else {
                            JSONArray array = JSONArray.parseArray(computeType.getComputeParam());
                            if (CollectionUtil.isNotEmpty(array)) {
                                for (int i = 0; i < array.size(); i++) {
                                    JSONObject object = array.getJSONObject(i);
                                    int minValue = FileElseUtil.getObjectToInt(object.getInteger("minValue"));
                                    int maxValue = FileElseUtil.getObjectToInt(object.getInteger("maxValue"));
                                    if (data.getNum() >= minValue && data.getNum() < maxValue) {
                                        value = FileElseUtil.getObjectToDouble(object.getDouble("score"));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    m.put(key, value);
                    valueMap.put(data.getSub_id(), m);
                }
                //封装
                SystemsDynamic dynamic = new SystemsDynamic();
                dynamic.setSysId(systemsDynamicVo.getSysId());
                dynamic.setPostureId(data.getStay_id());
                dynamic.setNumber(data.getNum());
                dynamic.setTargetId(data.getSub_id());
                dynamic.setType(1);
                return dynamic;
            }).collect(Collectors.toList());
            systemsDynamicService.saveBatch(dynamicList);
        }
        //图表封装
        List<String> xAxis = new ArrayList<>();
        List<Integer> yAxis = new ArrayList<>();
        for (String str : numMap.keySet()) {
            xAxis.add(str);
            yAxis.add(numMap.get(str));
        }
        Map<String, Object> chart = new HashMap<>();
        chart.put("xAxis", xAxis);
        chart.put("yAxis", yAxis);
        //分析
        List<Map<String, Object>> table = new ArrayList<>();
        List<String> targetList = redisUseService.getSystemsTargetList(systemsDynamicVo.getSysId());
        for (String targetId : targetList) {
            Map<String, Object> t = new HashMap<>();
            t.put("target_id", targetId);
            t.put("target_name", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
            String stay_target = "";
            double stay_score = 0;
            Map<String, Double> map = valueMap.get(targetId);
            if (ObjectUtil.isNotEmpty(map)) {
                int sign = 0;
                for (String s : map.keySet()) {
                    if (0 == sign) {
                        stay_target = s;
                    } else {
                        stay_target += "," + s;
                    }
                    stay_score += map.get(s);
                    sign++;
                }
            }
            t.put("stay_target", stay_target);
            t.put("stay_score", stay_score);
            t.put("score", stay_score);
            t.put("exercise_score", 0);
            table.add(t);
        }
        //排序
        table.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                double v1 = FileElseUtil.getObjectToDouble(o1.get("score"));
                double v2 = FileElseUtil.getObjectToDouble(o2.get("score"));
                return Double.compare(v2, v1);
            }
        });
        int sort = 1;
        for (Map<String, Object> map : table) {
            map.put("sort", sort);
            sort++;
        }
        resultMap.put("chart", chart);
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result getIntentionAnalyse(SystemsDynamicVo systemsDynamicVo) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Double> numMap = new HashMap<>();
        //处理停驻列表
        systemsDynamicService.lambdaUpdate()
                .eq(SystemsDynamic::getSysId, systemsDynamicVo.getSysId())
                .eq(SystemsDynamic::getType, 3)
                .remove();
        if (CollectionUtil.isNotEmpty(systemsDynamicVo.getParamList())) {
            List<SystemsDynamic> dynamicList = systemsDynamicVo.getParamList().stream().map(data -> {
                //得分
                if (null != data.getNum() && StringUtils.isNotBlank(data.getSub_id())) {
                    double value = FileElseUtil.getObjectToDouble(data.getNum());
                    double old = 0;
                    if (null != numMap.get(data.getSub_id())) {
                        old = numMap.get(data.getSub_id());
                    }
                    numMap.put(data.getSub_id(), old + value);
                }
                //封装
                SystemsDynamic dynamic = new SystemsDynamic();
                dynamic.setSysId(systemsDynamicVo.getSysId());
                dynamic.setNumber(data.getNum());
                dynamic.setTargetId(data.getSub_id());
                dynamic.setType(3);
                return dynamic;
            }).collect(Collectors.toList());
            systemsDynamicService.saveBatch(dynamicList);
        }
        //分析
        List<Map<String, Object>> table = new ArrayList<>();
        List<String> targetList = redisUseService.getSystemsTargetList(systemsDynamicVo.getSysId());
        for (String targetId : targetList) {
            Map<String, Object> t = new HashMap<>();
            t.put("target_id", targetId);
            t.put("target_name", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
            double score = 0;
            if (null != numMap.get(targetId)) {
                score = FileElseUtil.getObjectToDouble(numMap.get(targetId));
            }
            t.put("score", score);
            table.add(t);
        }
        //排序
        table.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                double v1 = FileElseUtil.getObjectToDouble(o1.get("score"));
                double v2 = FileElseUtil.getObjectToDouble(o2.get("score"));
                return Double.compare(v2, v1);
            }
        });
        int sort = 1;
        for (Map<String, Object> map : table) {
            map.put("sort", sort);
            sort++;
        }
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result getSystemsActiveAnalyse(SystemsDynamicVo systemsDynamicVo) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> numMap = new HashMap<>();
        //
        Map<String, Map<String, Double>> valueMap = new HashMap<>();
        //处理停驻列表
        systemsDynamicService.lambdaUpdate()
                .eq(SystemsDynamic::getSysId, systemsDynamicVo.getSysId())
                .eq(SystemsDynamic::getType, 2)
                .remove();
        if (CollectionUtil.isNotEmpty(systemsDynamicVo.getParamList())) {
            List<SystemsDynamic> dynamicList = systemsDynamicVo.getParamList().stream().map(data -> {
                //得分
                if (null != data.getNum() && StringUtils.isNotBlank(data.getStay_id()) && StringUtils.isNotBlank(data.getSub_id())) {
                    Map<String, Double> m = new HashMap<>();
                    if (null != valueMap.get(data.getSub_id())) {
                        m = valueMap.get(data.getSub_id());
                    }
                    String key = redisUseService.getPostureTypeName(data.getStay_id());
                    double value = 0;
                    //图表
                    Integer number = 0;
                    if (null != numMap.get(key)) {
                        number = numMap.get(key);
                    }
                    number += data.getNum();
                    numMap.put(key, number);
                    PostureComputeType computeType = postureComputeTypeService.getById(data.getStay_id());
                    if (ObjectUtil.isNotEmpty(computeType)) {
                        if ("1".equals(computeType.getComputeType())) {
                            JSONObject object = JSONObject.parseObject(computeType.getComputeParam());
                            value = object.getDouble("field") * data.getNum();
                        } else {
                            JSONArray array = JSONArray.parseArray(computeType.getComputeParam());
                            if (CollectionUtil.isNotEmpty(array)) {
                                for (int i = 0; i < array.size(); i++) {
                                    JSONObject object = array.getJSONObject(i);
                                    int minValue = FileElseUtil.getObjectToInt(object.getInteger("minValue"));
                                    int maxValue = FileElseUtil.getObjectToInt(object.getInteger("maxValue"));
                                    if (data.getNum() >= minValue && data.getNum() < maxValue) {
                                        value = FileElseUtil.getObjectToDouble(object.getDouble("score"));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    m.put(key, value);
                    valueMap.put(data.getSub_id(), m);
                }
                //封装
                SystemsDynamic dynamic = new SystemsDynamic();
                dynamic.setSysId(systemsDynamicVo.getSysId());
                dynamic.setPostureId(data.getStay_id());
                dynamic.setNumber(data.getNum());
                dynamic.setTargetId(data.getSub_id());
                dynamic.setType(2);
                return dynamic;
            }).collect(Collectors.toList());
            systemsDynamicService.saveBatch(dynamicList);
        }
        //图表封装
        List<String> xAxis = new ArrayList<>();
        List<Integer> yAxis = new ArrayList<>();
        for (String str : numMap.keySet()) {
            xAxis.add(str);
            yAxis.add(numMap.get(str));
        }
        Map<String, Object> chart = new HashMap<>();
        chart.put("xAxis", xAxis);
        chart.put("yAxis", yAxis);
        //分析
        List<Map<String, Object>> table = new ArrayList<>();
        List<String> targetList = redisUseService.getSystemsTargetList(systemsDynamicVo.getSysId());
        for (String targetId : targetList) {
            Map<String, Object> t = new HashMap<>();
            t.put("target_id", targetId);
            t.put("target_name", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
            String stay_target = "";
            double stay_score = 0;
            Map<String, Double> map = valueMap.get(targetId);
            if (ObjectUtil.isNotEmpty(map)) {
                int sign = 0;
                for (String s : map.keySet()) {
                    if (0 == sign) {
                        stay_target = s;
                    } else {
                        stay_target += "," + s;
                    }
                    stay_score += map.get(s);
                    sign++;
                }
            }
            t.put("stay_target", stay_target);
            t.put("score", stay_score);
            table.add(t);
        }
        //排序
        table.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                double v1 = FileElseUtil.getObjectToDouble(o1.get("score"));
                double v2 = FileElseUtil.getObjectToDouble(o2.get("score"));
                return Double.compare(v2, v1);
            }
        });
        int sort = 1;
        for (Map<String, Object> map : table) {
            map.put("sort", sort);
            sort++;
        }
        resultMap.put("chart1", chart);
        resultMap.put("chart2", chart);
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result getRelationAnalyse(SystemsDynamicVo systemsDynamicVo) {
        Map<String, Object> resultMap = new HashMap<>();
        //计算体系单个目标得分
        List<String> targetList = redisUseService.getSystemsTargetList(systemsDynamicVo.getSysId());
        List<TargetData> targetData = targetMapper.getTargetList(targetList);
        Map<String, Object> valueMap = new HashMap<>();
        targetData.forEach(data -> {
            valueMap.put(data.getTargetId(), FileElseUtil.getObjectToDouble(data.getIndexValue()));
        });
        Map<String, Double> targetValue = new HashMap<>();
        List<SystemsRelationship> list = targetMapper.getSystemsToMap(systemsDynamicVo.getSysId());
        //关系echar图
        resultMap.put("chart", selectSystemsRelationShip(list));
        //计算体系关系目标之间得分
        Map<String, List<String>> rList = new HashMap<>();
        int size = 0;
        if (CollectionUtil.isNotEmpty(list)) {
            for (SystemsRelationship ship : list) {
                double tV = 0;
                if (ship.getPoint().contains("1指向")) {
                    List<String> r = new ArrayList<>();
                    if (null != rList.get(ship.getTargetOne())) {
                        r = rList.get(ship.getTargetOne());
                    }
                    r.add(FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + ship.getTargetTwo(), "targetName")));
                    r.add(FileElseUtil.getObjectToString(valueMap.get(ship.getTargetTwo())));
                    if (r.size() > size) {
                        size = r.size();
                    }
                    rList.put(ship.getTargetOne(), r);
                    if (null != targetValue.get(ship.getTargetOne())) {
                        tV = FileElseUtil.getObjectToDouble(targetValue.get(ship.getTargetOne()));
                    }
                    targetValue.put(ship.getTargetOne(), tV + FileElseUtil.getObjectToDouble(valueMap.get(ship.getTargetTwo())));
                } else if (ship.getPoint().contains("2指向")) {
                    List<String> r = new ArrayList<>();
                    if (null != rList.get(ship.getTargetTwo())) {
                        r = rList.get(ship.getTargetTwo());
                    }
                    r.add(FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + ship.getTargetOne(), "targetName")));
                    r.add(FileElseUtil.getObjectToString(valueMap.get(ship.getTargetOne())));
                    if (r.size() > size) {
                        size = r.size();
                    }
                    rList.put(ship.getTargetTwo(), r);
                    if (null != targetValue.get(ship.getTargetTwo())) {
                        tV = FileElseUtil.getObjectToDouble(targetValue.get(ship.getTargetTwo()));
                    }
                    targetValue.put(ship.getTargetTwo(), tV + FileElseUtil.getObjectToDouble(valueMap.get(ship.getTargetOne())));
                }
            }
        }
        List<Object> table = new ArrayList<>();
        //头部信息封装
        List<String> header = new ArrayList<>();
        header.add("目标");
        if (size > 0) {
            int sign = 1;
            int middle = 1;
            for (int i = 0; i < size; i++) {
                if (middle == 1) {
                    header.add("关联子目标" + sign);
                    middle++;
                } else {
                    header.add("得分");
                    middle = 1;
                    sign++;
                }
            }
        }
        header.add("分值");
        header.add("排序");
        table.add(header);
        //目标关联得分排序
        if (CollectionUtil.isNotEmpty(targetList)) {
            List<List<Object>> mainData = new ArrayList<>();
            for (String targetId : targetList) {
                List<Object> t = new ArrayList<>();
                t.add(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName"));
                //关联关系记录
                if (size > 0) {
                    if (null != rList.get(targetId)) {
                        List<String> strings = rList.get(targetId);
                        for (String str : strings) {
                            t.add(str);
                        }
                        if (size - strings.size() > 0) {
                            for (int i = 0; i < size - strings.size(); i++) {
                                t.add("");
                            }
                        }
                    } else {
                        for (int i = 0; i < size; i++) {
                            t.add("");
                        }
                    }
                }
                t.add(FileElseUtil.getObjectToDouble(targetValue.get(targetId)));
                mainData.add(t);
            }
            //得分大小
            mainData.sort(new Comparator<List<Object>>() {
                @Override
                public int compare(List<Object> o1, List<Object> o2) {
                    double v1 = FileElseUtil.getObjectToDouble(o1.get(o1.size() - 1));
                    double v2 = FileElseUtil.getObjectToDouble(o2.get(o2.size() - 1));
                    return Double.compare(v2, v1);
                }
            });
            int sort = 1;
            for (List<Object> mainDatum : mainData) {
                mainDatum.add(sort);
                sort++;
            }
            table.addAll(mainData);
        }
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result getOverallAnalyse(SystemsDynamicVo systemsDynamicVo) {
        //扇形图
        String[] strs = {"静态分析","规律分析","动态分析","意图分析","关联分析"};
        //指标
        List<Map<String, String>> indicator = Arrays.stream(strs).map(data -> {
            Map<String, String> map = new HashMap<>();
            map.put("name", data);
            return map;
        }).collect(Collectors.toList());
        //目标整体得分
        List<Map<String, Object>> seriesData = new ArrayList<>();

        //头部
        List<Map<String, Object>> header = new ArrayList<>();
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "目标");
            map.put("child", ListUtil.empty());
            header.add(map);
        }
        //目标得分
        List<List<Object>> dataList = new ArrayList<>();
        //静态
        Map<String, Double> targetStatic = new HashMap<>();
        Map<String, List<Object>> targetIndexStatic = new HashMap<>();
        List<String> staticHeader = overall.getSystemsTargetStaticAnalyse(systemsDynamicVo.getSysId(), targetStatic, targetIndexStatic);
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "静态分析");
            map.put("child", staticHeader);
            header.add(map);
        }
        //规律
        Map<String, Double> targetRule = new HashMap<>();
        Map<String, List<Object>> targetIndexRule = new HashMap<>();
        List<String> ruleHeader = overall.getRuleAnalyse(systemsDynamicVo.getSysId(), targetRule, targetIndexRule);
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "规律分析");
            map.put("child", ruleHeader);
            header.add(map);
        }
        //动态
        Map<String, Double> targetActive = new HashMap<>();
        Map<String, List<Object>> targetIndexActive = new HashMap<>();
        List<String> activeHeader = overall.getActiveAnalyse(systemsDynamicVo.getSysId(), targetActive, targetIndexActive);
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "动态分析");
            map.put("child", activeHeader);
            header.add(map);
        }
        //意图
        Map<String, Double> targetIntention = new HashMap<>();
        Map<String, List<Object>> targetIndexIntention = new HashMap<>();
        List<String> intentionHeader = overall.getIntentionAnalyse(systemsDynamicVo.getSysId(), targetIntention, targetIndexIntention);
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "意图分析");
            map.put("child", intentionHeader);
            header.add(map);
        }
        //关联
        Map<String, Double> targetRelation = new HashMap<>();
        Map<String, List<Object>> targetIndexRelation = new HashMap<>();
        List<String> relationHeader = overall.getRelationAnalyse(systemsDynamicVo.getSysId(), targetRelation, targetIndexRelation);
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "关联分析");
            map.put("child", relationHeader);
            header.add(map);
        }
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "分值");
            map.put("child", ListUtil.empty());
            header.add(map);
        }
        {
            Map<String, Object> map = new HashMap<>();
            map.put("name", "排序");
            map.put("child", ListUtil.empty());
            header.add(map);
        }
        List<String> targetList = redisUseService.getSystemsTargetList(systemsDynamicVo.getSysId());
        if (CollectionUtil.isNotEmpty(targetList)) {
            for (String targetId : targetList) {
                double total = 0;
                //表格列表得分
                List<Object> targetData = new ArrayList<>();
                //扇形得分
                List<Double> targetValue = new ArrayList<>();
                //目标名称
                targetData.add(FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
                //静态得分
                targetData.addAll(targetIndexStatic.get(targetId));
                targetValue.add(targetStatic.get(targetId));
                total += targetStatic.get(targetId);
                //规律得分
                targetData.addAll(targetIndexRule.get(targetId));
                targetValue.add(targetRule.get(targetId));
                total += targetRule.get(targetId);
                //动态得分
                targetData.addAll(targetIndexActive.get(targetId));
                targetValue.add(targetActive.get(targetId));
                total += targetActive.get(targetId);
                //意图得分
                targetData.addAll(targetIndexIntention.get(targetId));
                targetValue.add(targetIntention.get(targetId));
                total += targetIntention.get(targetId);
                //关联得分
                targetData.addAll(targetIndexRelation.get(targetId));
                targetValue.add(targetRelation.get(targetId));
                total += targetRelation.get(targetId);
                //表格数据封装
                targetData.add(FileElseUtil.getObjectToDouble(total));
                dataList.add(targetData);
                //扇形数据
                if (total > 0) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("name", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName")));
                    m.put("value", targetValue);
                    seriesData.add(m);
                }
            }
        }
        dataList.sort(new Comparator<List<Object>>() {
            @Override
            public int compare(List<Object> o1, List<Object> o2) {
                double v1 = FileElseUtil.getObjectToDouble(o1.get(o1.size() - 1));
                double v2 = FileElseUtil.getObjectToDouble(o2.get(o2.size() - 1));
                return Double.compare(v2, v1);
            }
        });
        int sort = 1;
        for (List<Object> list : dataList) {
            list.add(sort);
            sort++;
        }
        //返回数据封装
        Map<String, Object> resultMap = new HashMap<>();
        //扇形图封装
        Map<String, Object> chart = new HashMap<>();
        chart.put("indicator", indicator);
        chart.put("seriesData", seriesData);
        resultMap.put("chart", chart);
        //表格
        Map<String, Object> table = new HashMap<>();
        table.put("header", header);
        table.put("dataList", dataList);
        //主体
        resultMap.put("table", table);
        return ResultUtil.success(resultMap);
    }

    public Map<String, Object> selectSystemsRelationShip(List<SystemsRelationship> relationships) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("edges", ListUtil.empty());
        resultMap.put("nodes", ListUtil.empty());
        if (CollectionUtil.isNotEmpty(relationships)) {
            ArrayList<JSONObject> parentList = new ArrayList<>();
            List<JSONObject> list = new ArrayList<>();
            Map<String, Set<String>> cMap = new HashMap<>();
            Map<String, String> tMap = new HashMap<>();
            LinkedHashSet lhs = new LinkedHashSet();
            for (SystemsRelationship relationship : relationships) {
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetOne())
                        && redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetTwo())) {
                    String subOneName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetOne(), "targetName").toString();
                    String subTwoName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetTwo(), "targetName").toString();

                    JSONObject parent = new JSONObject();
                    parent.put("name", subOneName);
                    JSONObject parentRelation = new JSONObject();
                    parentRelation.put("name", subTwoName);
                    parentList.add(parentRelation);
                    parentList.add(parent);

                    //关系图
                    String one = subOneName + "&&" + subTwoName;
                    String two = subTwoName + "&&" + subOneName;
                    if (null == cMap.get(one)) {
                        if (null == cMap.get(two)) {
                            if ("目标1指向目标2".equals(relationship.getPoint())) {
                                tMap.put(one, "1");
                            } else if ("目标2指向目标1".equals(relationship.getPoint())) {
                                tMap.put(one, "2");
                            } else {
                                tMap.put(one, "3");
                            }
                            Set<String> set = new HashSet<>();
                            set.add(relationship.getRelationType());
                            cMap.put(one, set);
                        } else {
                            Set<String> set = cMap.get(two);
                            set.add(relationship.getRelationType());
                            cMap.put(two, set);
                        }
                    } else {
                        Set<String> set = cMap.get(one);
                        set.add(relationship.getRelationType());
                        cMap.put(one, set);
                    }
                }
            }
            for (String s : tMap.keySet()) {
                JSONObject children = new JSONObject();
                if ("1".equals(tMap.get(s))) {
                    children.put("source", s.split("&&")[0]);//父级名称
                    children.put("target", s.split("&&")[1]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                } else if ("2".equals(tMap.get(s))) {
                    children.put("source", s.split("&&")[1]);//父级名称
                    children.put("target", s.split("&&")[0]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                } else {
                    children.put("source", s.split("&&")[0]);//父级名称
                    children.put("target", s.split("&&")[1]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                    JSONObject childrenRelation = new JSONObject();
                    childrenRelation.put("source", s.split("&&")[1]);//子级名称
                    childrenRelation.put("target", s.split("&&")[0]);//父级名称
                    childrenRelation.put("value", "");//关系
                    list.add(childrenRelation);
                }
                list.add(children);
            }
            lhs.addAll(parentList);
            resultMap.put("edges", list);
            resultMap.put("nodes", lhs);
        }
        return resultMap;
    }

    private CellStyle createWrappedAndCenteredCellStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();

        // 设置自动换行
        cellStyle.setWrapText(true);

        // 设置水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        // 设置垂直居中（可选，如果你需要垂直居中的话）
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        cellStyle.setBorderTop(BorderStyle.THIN); // 设置上边框为细线
        cellStyle.setBorderBottom(BorderStyle.THIN); // 设置下边框为细线
        cellStyle.setBorderLeft(BorderStyle.THIN); // 设置左边框为细线
        cellStyle.setBorderRight(BorderStyle.THIN); // 设置右边框为细线

        return cellStyle;
    }

    private double getTotal(Set targetIds, double total, Map<Object, Object> main) {
        for (Object targetId : targetIds) {
            if (redisUtil.hasKey(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1)) {
                Map<Object, Object> map = redisUtil.hmget(RedisName.SYSTEMS_TARGET_SUB_LEVEL_VALUE + "_" + targetId + "_" + 1);
                for (Object o : map.keySet()) {
                    total += FileElseUtil.getObjectToDouble(map.get(o));
                    if (null == main.get(o)) {
                        main.put(o, FileElseUtil.getObjectToDouble(map.get(o)));
                    } else {
                        double tV = FileElseUtil.getObjectToDouble(main.get(o));
                        double oV = FileElseUtil.getObjectToDouble(map.get(o));
                        main.put(o, tV + oV);
                    }
                }
            }
        }
        return total;
    }

}
